<?php

namespace addons\shopro\listener;

use addons\shopro\service\commission\Agent;
use app\admin\model\shopro\commission\Order as CommissionOrderModel;
use addons\shopro\service\commission\Order as OrderService;
use addons\shopro\service\commission\Reward as RewardService;
use addons\shopro\service\commission\Agent as AgentService;
use app\admin\model\shopro\commission\Order as OrderModel;
use app\admin\model\shopro\commission\Reward as RewardModel;
use app\admin\model\shopro\data\Richtext;
use app\admin\model\shopro\Share as ShareModel;
use app\common\model\Msg;
use think\Log;

class Commission
{

    /**
     * 用户注册成功
     */
    public function userRegisterAfter($payload)
    {
        $shareInfo = request()->param('shareInfo/a');

        if ($shareInfo) {
            // 注册后添加分享信息
            ShareModel::log($payload['user'], $shareInfo);
        }
        $agent = new AgentService($payload['user']);

        $agent->createNewAgent('user');

        // 获取系统的平台介绍配置
        $detail = Richtext::where(['id' => 1])->value('content');
        Msg::addMsg($payload['user']['id'], '尊敬的用户您好，欢迎来到油爱寄信平台~', $detail);
    }

    /**
     * 用户分享行为后
     */
    public function userShareAfter($payload)
    {
        $shareInfo = $payload['shareInfo'];
        Log::error('进来用户分享行为后：' . json_encode($shareInfo));

        if ($shareInfo) {

            $user_id = intval($shareInfo->user_id); // 受邀用户

            $share_id = intval($shareInfo->share_id); // 邀请人

            $agent = new AgentService($user_id);

            $bindCheck = $agent->bindUserRelation('share', $share_id);

            // 统计单链业绩
            if ($bindCheck) {
                $agent->createAsyncAgentUpgrade($user_id);

                $share_reward = config('site.share_reward');


                Log::error('用户分享行为后-进来统计单链业绩：' . json_encode([
                        'buyer_id' => $user_id,
                        'agent_id' => $share_id,
                        'share_reward' => $share_reward,
                    ]));

                if ($share_reward) {

                    Log::error('用户分享行为后-开启了邀请新用户获得奖励');

                    $commissionOrder = OrderModel::where([
                        'reward_type' => 'share_self_price',
                        'buyer_id' => $user_id,
                        'agent_id' => $share_id,
                    ])->find();
                    if (!$commissionOrder) {
                        $share_self_get = config('site.share_self_get');
                        Log::error('用户分享行为后-进来统计单链业绩2：' . $share_self_get);
                        // 2025-07-17 新增邀请成功  新增奖励
                        $commissionOrderParams = [
                            'self_buy' => 0,
                            'order_id' => 0,
                            'order_item_id' => 0,
                            'buyer_id' => $user_id,
                            'goods_id' => 0,
                            'agent_id' => $share_id,
                            'amount' => $share_self_get,
                            'reward_type' => 'share_self_price',
                            'commission_rules' => '',
                            'reward_event' => 'share',
                            'commission_order_status' => 0,  // 是否计入分销业绩
                            'commission_reward_status' => RewardModel::COMMISSION_REWARD_STATUS_PENDING,  // 佣金状态
                        ];

                        $commissionOrder = OrderModel::create($commissionOrderParams);


                        if ($share_self_get > 0) {
                            // 防止重复添加佣金
                            $commissionReward = RewardModel::where([
                                'commission_order_id' => $commissionOrder->id,
                                'agent_id' => $share_id,
                                'commission_level' => 0,   // 分佣层级
                            ])->find();

                            if (!$commissionReward) {
                                $currentAgent = new Agent($share_id);
                                $currentAgentLevel = $currentAgent->getAgentLevel();
                                $commissionRewardParams = [
                                    'order_id' => $commissionOrder->order_id,
                                    'order_item_id' => $commissionOrder->order_item_id,
                                    'buyer_id' => $commissionOrder->buyer_id,      // 购买人
                                    'commission_order_id' => $commissionOrder->id,   // 分销订单ID
                                    'agent_id' => $share_id,           // 待分佣分销商ID
                                    'type' => 'commission',                               // 奖金类型
                                    'commission' => $share_self_get,                     // 佣金
                                    'status' => 0,                              // 佣金状态
                                    'original_commission' => $share_self_get,            // 原始佣金
                                    'commission_level' => 0,   // 分佣层级
                                    'commission_rules' => '',   // 分佣层级
                                    'agent_level' => $currentAgentLevel              // 分佣时分销商等级
                                ];
                                $commissionReward = RewardModel::create($commissionRewardParams);
                                // 支付后拨款
                                (new RewardService('share'))->runCommissionRewardByOrder($commissionOrder);
                                Log::error('用户分享行为后-进来统计单链业绩5：' . json_encode($commissionReward));
                            }
                        }
                    }


                    $commissionOrder1 = OrderModel::where([
                        'reward_type' => 'share_new_price',
                        'buyer_id' => $user_id,
                        'agent_id' => $user_id,
                    ])->find();
                    if (!$commissionOrder1) {
                        $share_new_get = config('site.share_new_get');
                        Log::error('用户分享行为后-进来统计单链业绩66：' . $share_new_get);
                        // 2025-07-17 新增邀请成功  新增奖励
                        $commissionOrderParams1 = [
                            'self_buy' => 0,
                            'order_id' => 0,
                            'order_item_id' => 0,
                            'buyer_id' => $user_id,
                            'goods_id' => 0,
                            'agent_id' => $user_id,
                            'amount' => $share_new_get,
                            'reward_type' => 'share_new_price',
                            'commission_rules' => '',
                            'reward_event' => 'share',
                            'commission_order_status' => 0,  // 是否计入分销业绩
                            'commission_reward_status' => RewardModel::COMMISSION_REWARD_STATUS_PENDING,  // 佣金状态
                        ];

                        $commissionOrder1 = OrderModel::create($commissionOrderParams1);


                        if ($share_new_get > 0) {
                            // 防止重复添加佣金
                            $commissionReward1 = RewardModel::where([
                                'commission_order_id' => $commissionOrder1->id,
                                'agent_id' => $user_id,
                                'commission_level' => 0,   // 分佣层级
                            ])->find();

                            if (!$commissionReward1) {
                                $currentAgent1 = new Agent($user_id);
                                $currentAgentLevel1 = $currentAgent1->getAgentLevel();
                                $commissionRewardParams1 = [
                                    'order_id' => $commissionOrder1->order_id,
                                    'order_item_id' => $commissionOrder1->order_item_id,
                                    'buyer_id' => $commissionOrder1->buyer_id,      // 购买人
                                    'commission_order_id' => $commissionOrder1->id,   // 分销订单ID
                                    'agent_id' => $user_id,           // 待分佣分销商ID
                                    'type' => 'commission',                               // 奖金类型
                                    'commission' => $share_new_get,                     // 佣金
                                    'status' => 0,                              // 佣金状态
                                    'original_commission' => $share_new_get,            // 原始佣金
                                    'commission_level' => 0,   // 分佣层级
                                    'commission_rules' => '',   // 分佣层级
                                    'agent_level' => $currentAgentLevel1              // 分佣时分销商等级
                                ];
                                $commissionReward1 = RewardModel::create($commissionRewardParams1);
                                // 支付后拨款
                                (new RewardService('share'))->runCommissionRewardByOrder($commissionOrder1);
                                Log::error('用户分享行为后-进来统计单链业绩77：' . json_encode($commissionReward1));
                            }
                        }
                    }

                }
            }
        }
    }

    /**
     * 订单支付后
     */
    public function orderPaidAfter($params)
    {
        // 订单支付成功
        $order = $params['order'];

        // 积分商品订单不参与分销
        if ($order['type'] === 'score') return;

        $user = $params['user'];

        $agent = new AgentService($user);

        // 绑定用户关系
        $agent->bindUserRelation('pay');

        // 先记录分佣 再处理记录业绩、升级等情况
        $items = $order ? $order['items'] : [];

        foreach ($items as $item) {
            if (isset($item['ext']['is_commission']) && !$item['ext']['is_commission']) continue;

            $commission = new OrderService($item);
            // 检查能否分销
            if (!$commission->checkAndSetCommission()) continue;
            // 添加分销订单
            $commissionOrder = $commission->createCommissionOrder();

            if (!$commissionOrder) continue;

            // 执行佣金计划
            $commission->runCommissionPlan($commissionOrder);
            // 支付后拨款
            (new RewardService('paid'))->runCommissionRewardByOrder($commissionOrder);
        }

        // 创建分销商
        $agent->createNewAgent();
        // 分销商数据统计&升级(异步执行) 
        $agent->createAsyncAgentUpgrade();
    }

    // 线下付款后
    public function orderOfflinePaidAfter($params)
    {
        $this->orderPaidAfter($params);
    }

    /**
     * 订单确认收货
     */
    public function orderConfirmFinish($params)
    {
        $order = $params['order'];

        $service = new RewardService('confirm');
        $commissionOrders = collection(CommissionOrderModel::where('order_id', $order->id)->select());
        $commissionOrders->each(function ($commissionOrder) use ($service) {
            $service->runCommissionRewardByOrder($commissionOrder);
        });
    }

    /**
     * 订单完成
     */
    public function orderFinish($params)
    {
        $order = $params['order'];

        $service = new RewardService('finish');
        $commissionOrders = collection(CommissionOrderModel::where('order_id', $order->id)->select());
        $commissionOrders->each(function ($commissionOrder) use ($service) {
            $service->runCommissionRewardByOrder($commissionOrder);
        });
    }

    /**
     * 订单退款后
     */
    public function orderItemRefundAfter($params)
    {
        $order = $params['order'];
        $item = $params['item'];

        $commissionOrder = CommissionOrderModel::where('order_id', $order->id)->where('order_item_id', $item->id)->find();

        if (!$commissionOrder) return;

        (new RewardService('refund'))->backCommissionRewardByOrder($commissionOrder);
    }
}
